<template>
  <div>
    <div class="dashboard-container">
      <div class="app-container">
        <page-tools :show-before="true">
          <span slot="before">总共{{ page.total }}条数据</span>
          <template slot="after">
            <el-button size="small" type="warning" @click="$router.push('/import')">导入</el-button>
            <el-button size="small" type="danger" @click="deriveFn">导出</el-button>
            <el-button v-if="buttonVali('addUser')" size="small" type="primary" @click="showDialog=true">新增员工</el-button>
          </template>
        </page-tools>
        <!-- 放置表格和分页 -->
        <el-card>
          <el-table border :data="list">
            <el-table-column type="index" label="序号" sortable="" />
            <el-table-column label="头像">
              <template #default="{row}">
                <img
                  v-imgerr="require('@/assets/common/bigUserHeader.png')"
                  style="width:64px;height:64px"
                  :src="row.staffPhoto"
                  alt=""
                  @click="showCode(row.staffPhoto)"
                >
              </template>
            </el-table-column>
            <el-table-column prop="username" label="姓名" sortable="" />
            <el-table-column prop="workNumber" label="工号" sortable="" />
            <el-table-column prop="formOfEmployment" label="聘用形式" :formatter="formatterHireShape" sortable="" />
            <el-table-column prop="departmentName" label="部门" sortable="" />
            <el-table-column prop="timeOfEntry" label="入职时间" sortable="">
              <template #default="{row}">
                {{ row.timeOfEntry|formatDate }}
              </template>
            </el-table-column>
            <el-table-column prop="enableState" label="账户状态" sortable="">
              <template #default="{row}">
                <el-switch :value="row.enableState===1" />
              </template>
            </el-table-column>
            <el-table-column label="操作" sortable="" fixed="right" width="280">
              <template #default="{row}">
                <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
                <el-button type="text" size="small">转正</el-button>
                <el-button type="text" size="small">调岗</el-button>
                <el-button type="text" size="small">离职</el-button>
                <el-button type="text" size="small" @click="dialogRols(row.id)">角色</el-button>
                <el-button type="text" size="small" @click="remove(row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页组件 -->
          <el-row type="flex" justify="center" align="middle" style="height: 60px">
            <el-pagination
              layout="prev, pager, next"
              :total="page.total"
              :page-size="page.size"
              @current-change="currentchange"
            />
          </el-row>
        </el-card>
        <AddEmployee :show-dialog.sync="showDialog" @submitFn="getStaffLists" />
        <AssignRols ref="ARols" :show-dialog.sync="showRols" />
        <el-dialog title="二维码" :visible="isSHOW" @close="isSHOW=false">
          <center>
            <canvas ref="Mycanvas" />
          </center>

        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script>
import { getStaffLists, deleteStaff } from '@/api/staff'
import employees from '@/api/constant/employees'
import { formatDate } from '@/filters'
import AddEmployee from './components/add-employee.vue'
import QRcode from 'qrcode'
import AssignRols from './components/assign-rols.vue'
export default {
  components: {
    AddEmployee,
    AssignRols
  },
  props: {

  },
  data() {
    return {
      list: [],
      page: {
        page: 1,
        size: 5,
        total: 0
      },
      showDialog: false,
      isSHOW: false,
      showRols: false
    }
  },

  created() {
    this.getStaffLists()
  },
  mounted() {

  },
  methods: {
    async dialogRols(id) {
      await this.$refs.ARols.getUserDetailById(id)
      this.showRols = true
    },
    async getStaffLists() { // 页面获取数据
      const { rows, total } = await getStaffLists(this.page)
      this.list = rows.map(v => { // 改造数据 本地服务器没有改属性
        return {
          ...v,
          enableState: v.enableState || 1
        }
      })
      this.page.total = total
      this.$store.commit('user/setTotal', total)
    },
    currentchange(newpage) { // 分页切换
      this.page.page = newpage
      this.getStaffLists()
    },
    formatterHireShape(row, column, cellValue, index) { // 修改聘用形式列显示的数据
      const obj = employees.hireType.find(v => +v.id === +cellValue)
      return obj ? obj.value : '未知'
    },
    async deriveFn() { // 导出
      const { rows } = await getStaffLists({ page: this.page, size: this.page.total })
      // console.log(rows)
      const dict = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      const header = Object.keys(dict)
      console.log(header)
      const data = rows.map(v => {
        return this.obj2arr(v, dict)//
      })
      console.log(data)
      // 按需引入导出数据 exles
      const { export_json_to_excel } = await import('@/vendor/Export2Excel')
      export_json_to_excel({
        header,
        data
      })
    },
    obj2arr(user, dict) { // 改造数据
      const newArr = []
      for (const key in dict) {
        const enkey = dict[key]

        let value = user[enkey]
        if (enkey === 'formOfEmployment' && value === 1) {
          value = '正式工'
        } else if (enkey === 'formOfEmployment' && value !== 1) {
          value = '非正式'
        } else if (enkey === 'timeOfEntry' || enkey === 'correctionTime') {
          value = formatDate(value)// 修改时间格式
        }
        newArr.push(value)
      }
      return newArr
    },
    async remove(id) {
      await deleteStaff(id)
      await this.$confirm('您确认要删除吗？')
      // 如果当前显示的数据为一并且当前页不为一，显示的页面就减一，下次发请求就会到下一页
      if (this.list.length === 1 && this.page.page !== 1) {
        this.page.page -= 1
        this.getStaffLists()// 重新渲染后list才会发生改变
        this.$message.success('删除成功')
      }
      this.getStaffLists()
    },
    showCode(srcImg) {
      if (srcImg) {
        this.isSHOW = true
        this.$nextTick(() => {
          QRcode.toCanvas(this.$refs.Mycanvas, srcImg, {
            watch: 300,
            color: {
              dark: '#66b1ff'
            }
          })
        })
      }
    }
  }
}
</script>

<style scoped lang="less">

</style>
